<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>个人中心</title>
  <link rel="stylesheet" href="../lib/layui/css/layui.css">
  <link rel="stylesheet" href="../css/base.css">
  <link rel="stylesheet" href="../css/form.css">
</head>

<body>
  <div class="header container">个人中心
    <p style="display: block;">
      <a href="./rpwd.html">修改密码</a>
      <a href="./index.html">回到首页</a>
    </p>
  </div>
  <form class="layui-form" lay-filter="selfForm">
    <label>
      用户名： <input type="text" class="username" name="username" lay-verify="required" disabled>
    </label>
    <label>
      年龄： <input type="text" name="age" lay-verify="required" class="age">
    </label>
    <label>
      性别： <select class='gender' name="gender" lay-verify="required">
        <option value="">请选择</option>
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </label>
    <label>
      昵称： <input type="text" name="nickname" lay-verify="required" class="nickname">
    </label>
    <button lay-submit lay-filter="update">确认修改</button>
  </form>
  <script type="module">
    import '../lib/layui/layui.js'
    import '../lib/axios.js'

    const id = layui.data('shop').id

    axios.get(`http://localhost:9000/users/info?id=${id}`, { headers: { 'authorization': layui.data('shop').token } }).then(res => {
      if (res.data.code === 1) {
        layui.$('.username').val(res.data.user.username)
        layui.$('.age').val(res.data.user.age)
        layui.$('.gender').val(res.data.user.gender)
        layui.$('.nickname').val(res.data.user.nickname)
      }
    })

    layui.use(['form'], function () {
      var form = layui.form;
      var $ = layui.$;
      var layer = layui.layer;

      // 表单验证
      form.verify({
        required: function (value, item) {
          if (!value) {
            return '该项为必填项';
          }
        }
      });

      // 登录提交事件
      form.on('submit(update)', function (data) {
        var username = data.field.username;
        var age = data.field.age;
        var gender = data.field.gender;
        var nickname = data.field.nickname;

        axios.post('http://localhost:9000/users/update', {
          id: layui.data('shop').id,
          age: age,
          gender: gender,
          nickname: nickname
        })
      }, {
        headers: {
          'authorization': layui.data('shop').token
        }
      })
        .then(function (response) {
          if (response.data.code === 1) {
            layer.msg(response.data.message, { icon: 1 });
            layui.data('shop', {
              key: 'nickname',
              value: response.data.user.nickname
            })
          } else {
            layer.msg(response.data.message, { icon: 0 })
          }
        })

      return false;
    });


  </script>
</body>

</html>